# -*- coding: utf-8 -*-
"""
Created on Sat Dec 21 19:34:46 2024

@author: lenovo
"""
import os,re
from gsj_typhoon import split_str_id

# names = ['mojie28','dusurui16','gaemi09','haikui38','kangni54','shantuo44','saola25','koinu49']
names = ['2023NH42_36']
strings = []
numbers = []
basedir = r'D:\met_data\ty_ensemble'
tynames,tyids = split_str_id(names)

def clean(basedir):
    # basedir = D:\met_data\ty_ensemble\
    dates = os.listdir(basedir)
    for basedir2 in [os.path.join(basedir,date) for date in dates]:
        names = [file for file in os.listdir(basedir2) if file.startswith('TRACK_ID')]
        for name in names:
            os.remove(os.path.join(basedir2,name))

# 如果有的话，先清理掉痕迹
for name in names:
    clean(os.path.join(basedir,name))
    
for tyname,tyid in zip(tynames,tyids):
    directory= rf'D:\met_data\ty_ensemble\{tyname}_{tyid}'
    splitfile = rf"trmatch_cntl_tr00{tyid}"
    names=os.listdir(directory)
    files = [os.path.join(directory,f) for f in names ]
    
    
    for f in files:
        file_path = os.path.join(f,splitfile)  # 替换为你的文件路径
        try:
            with open(file_path, "r") as file:
                lines = file.readlines()  # 按行读取文件内容
        except Exception as e:
            print(f'no data {e}')
            continue
        
        # 得到开始行
        s=[]
        for i in range(len(lines)):
            if lines[i].startswith("TRACK_ID"):
                # 解析 TRA}}CK_ID 和 START_TIME
                s.append(i)        
        s.append( len(lines)-1 )
        
        
        # 选取单个台风数据，得到标题，并写入
        for t in range(len(s)-1):
            # 得到台风名
            i=s[t]
            nameline1 = lines[i]
            parts1 = nameline1.split()
            
            name=parts1[0]+"_"+parts1[1]
            # 
            with open(os.path.join(f,name) , "w") as file:
                file.writelines( lines[s[t]:s[t+1]] )  # 写入筛选后的行
            